package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.client.article.IArticleClient;
import com.heima.client.user.IUserClient;
import com.heima.client.wemedia.IWemediaClient;
import com.heima.comment.receive.pojos.ApComment;
import com.heima.comment.receive.pojos.ApCommentLike;
import com.heima.comment.receive.pojos.ApCommentRepay;
import com.heima.comment.receive.pojos.ApCommentRepayLike;
import com.heima.comment.service.ApCommentReplyService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.*;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticle;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ApCommentReplyServiceImpl implements ApCommentReplyService {
    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private IUserClient userClient;

    /**
     * 保存回复评论
     *
     * @param commentRepaySaveDto
     * @return
     */
    @Override
    public ResponseResult save(CommentRepaySaveDto commentRepaySaveDto) {
        if (commentRepaySaveDto == null || commentRepaySaveDto.getCommentId() == null || commentRepaySaveDto.getContent() == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        //1.判断当前登录的用户---正常继续流程，非正常直接返回
        Integer userId = ApThreadLocalUtil.get();
        //1.1 如果是非正常用户---需登录后才能操作,直接返回
        if (userId == null || userId == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        //2.评论内容不能超过140字
        if (commentRepaySaveDto.getContent().length() > 140)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //3.文本敏感词检测
        String content = commentRepaySaveDto.getContent();
        ResponseResult responseResult = wemediaClient.autoScan(content);
        boolean textIsPass = (boolean) responseResult.getData();
        if (!textIsPass) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //4.创建apCommentReply实体，准备保存数据
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id")
                .is(commentRepaySaveDto.getCommentId())), ApComment.class);
        BeanUtils.copyProperties(commentRepaySaveDto, apCommentRepay);
        ResponseResult result1 = userClient.queryUser(userId);
        ApUser apUser = JSON.parseObject(JSON.toJSONString(result1.getData()), ApUser.class);
        apCommentRepay.setAuthorId(Long.valueOf(apUser.getId()));
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setLikes(0L);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdateTime(new Date());
        apCommentRepay.setOperation((short)0);
        //4.1保存数据到MongoDB中
        mongoTemplate.save(apCommentRepay);
        //5.增加文章评论的回复数量
        if(apComment.getReply()==null){
            apComment.setReply(1);
        }else {
            apComment.setReply(apComment.getReply() + 1);
        }
        mongoTemplate.save(apComment);
        //6.文章评论数量+1
        Long entryId = apComment.getEntryId();
        ApArticle apArticle = JSON.parseObject(JSON.toJSONString(articleClient.queryArticle(entryId).getData()), ApArticle.class);
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(apArticle,articleDto);
        if(apArticle.getComment()==null){
            apArticle.setComment(1);
        }else {
            apArticle.setComment(apArticle.getComment()+1);
        }
        articleClient.syncArticle(articleDto);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询评论回复列表
     *
     * @param commentRepayDto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto commentRepayDto) {
        //校验参数
        if (commentRepayDto == null || commentRepayDto.getCommentId() == null||commentRepayDto.getMinDate() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (commentRepayDto.getSize() == null)
            commentRepayDto.setSize(10);
        //1.从mongodb查询最新时间ApCommentRepay的数据
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria
                        .where("commentId").is(commentRepayDto.getCommentId()).and("createdTime").lt(commentRepayDto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(commentRepayDto.getSize()), ApCommentRepay.class);
        //2.数据填充
        if (apCommentRepays==null)
            return ResponseResult.okResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            if(apCommentRepay!=null){
                apCommentRepay.setOperation((short)0);
            }else {
                break;
            }
        }
        return ResponseResult.okResult(apCommentRepays);
    }

    /**
     * 点赞 0：点赞 1：取消点赞
     *
     * @param commentRepayLikeDto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto commentRepayLikeDto) {
        String commentId = commentRepayLikeDto.getCommentRepayId();
        //获取当前作者ID
        Integer userId = ApThreadLocalUtil.get();
        //根据评论ID查询当前回复评论信息
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(
                Query.query(Criteria.where("id")
                        .is(commentId)),
                ApCommentRepay.class);
        //校验当然评论是否存在
        if (ObjectUtils.isEmpty(apCommentRepay)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (commentRepayLikeDto.getOperation() == (short)0) {
            //1.1修改当前评论的like字段+1
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.updateFirst(
                    Query.query(Criteria.where("commentId")
                            .is(commentId)),
                    new Update()
                            .set("likes", apCommentRepay.getLikes()),
                    ApCommentRepay.class);
            //1.2将作者信息保存到ap_comment_reply_like中
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setAuthorId(Long.valueOf(userId));
            mongoTemplate.save(apCommentRepayLike);
        } else {
            //2取消点赞
            //2取消点赞
            long tmp = apCommentRepay.getLikes() - 1;
            tmp = tmp < 1 ? 0 : tmp;
            apCommentRepay.setLikes(tmp);
            mongoTemplate.save(apCommentRepay);
            //删除ap_comment_reply_like表中的数据
            mongoTemplate.remove(Query.query(
                            Criteria.where("commentRepayId")
                                    .is(apCommentRepay.getCommentId())),
                    ApCommentRepayLike.class);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
